package fh.bsys.threading.classes;

/**
 * Threading Testclass for an unsynchronized access to a array of String.
 * The singleton pattern is used for this class, so you have to use the getInstance() Method.
 * @author muetze
 *
 */
public class Testtable_unsynched {
	String[] table;
	int cnt;
	private static Testtable_unsynched inst;
	
	private Testtable_unsynched() {
		this.cnt = 0;
		this.table = new String[1000];
	}
	
	public static Testtable_unsynched getInstance() {
		if (inst == null) {
			inst =  new Testtable_unsynched();
		}
		return inst;
	}
	
	/**
	 * returns the next free cell (index of the Stringarray)
	 * -1 if the end of the array is reached.
	 * @return int
	 */
	public int getNextCell() {
		if (cnt < table.length) {
			int buf = this.cnt;
			this.cnt++;
			return buf;
		}
		else
			return -1;
	}
	
	/**
	 * writes the String value to the specified cellnr (index of the array).
	 * if there is already a string, value will be concatenated to this string.
	 * @param value String
	 * @param cellnr int
	 */
	public void write(String value, int cellnr) {
		if (this.table[cellnr] == null) {
			this.table[cellnr] = value;
		}
		else
			this.table[cellnr] = this.table[cellnr].concat(value);
	}
	
	/**
	 * prints the whole array of strings to stdout
	 */
	public void print() {
		for (int i=0; i<table.length; i++) {
			System.out.println("CellNr " + i + " : " + table[i]);
		}
	}
}
